package com.clkj.mobileinspector.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.clkj.mobileinspector.R;
import com.clkj.mobileinspector.model.Constant;
import com.clkj.mobileinspector.model.ObserverOnNext;
import com.clkj.mobileinspector.model.OkHttpUtils;
import com.clkj.mobileinspector.model.bean.QueryBean;
import com.clkj.mobileinspector.model.bean.QuerySuccessBean;
import com.clkj.mobileinspector.model.bean.ResourceApi;
import com.clkj.mobileinspector.ui.adapter.SafeguardRigthRecordAdapter;
import com.clkj.mobileinspector.utils.JsonUtils;
import com.clkj.mobileinspector.utils.LogUtils;
import com.clkj.mobileinspector.utils.ResourceApiUtils;
import com.lws.basic.base.BaseActivity;
import com.lws.basic.utils.common.MyLogger;
import com.lws.basic.utils.common.MyToast;
import com.lws.basic.utils.common.TimeUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//维权记录
public class SafeguardRightsRecordActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {


    @BindView(R.id.et_safeguard_rights)
    EditText mEtSafeguardRights;
    @BindView(R.id.et_idcard)
    EditText mEtIdcard;
    @BindView(R.id.et_perpetrator)
    EditText mEtPerpetrator;
    @BindView(R.id.et_start)
    EditText mEtStart;
    @BindView(R.id.et_end)
    EditText mEtEnd;
    @BindView(R.id.rv)
    RecyclerView mRv;
    @BindView(R.id.srl)
    SmartRefreshLayout mSrl;
    SafeguardRigthRecordAdapter mAdapter;
    private int mPage;

    @Override
    public int setLayoutId() {
        return R.layout.activity_safeguard_rights_record;
    }


    @Override
    public void initData() {
        super.initData();
        ButterKnife.bind(this);
        initRv();
        initRefresh();
        getData(search());
    }

    /**
     * 初始化rv
     */
    private void initRv() {
        List<QuerySuccessBean.DataBean.DataListBean> list = new ArrayList<>();
        mRv.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new SafeguardRigthRecordAdapter(null);
        mRv.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
    }

    /**
     * 获取数据
     */
    private void getData(List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> keyValueListBeanList) {
        ResourceApi rightsRecordQuery = ResourceApiUtils.getResourceApi(MainActivity.resourceApiList, Constant.rightsRecordQuery);

        mPage = 1;
        showLoading();
        List<QueryBean.ParameterBean.OrderByBean> orderByList = new ArrayList<>();
//        QueryBean.ParameterBean.OrderByBean order1 = new QueryBean.ParameterBean.OrderByBean();
//        order1.setSort("passdate");
//        order1.setSort("desc");
//        orderByList.add(order1);


        QueryBean.ParameterBean.PageBean page = new QueryBean.ParameterBean.PageBean();
        page.setPageNo(1);
        page.setPageSize(20);

        String json = JsonUtils.query(keyValueListBeanList, "policename,policetype,offendername,createdate,id"
                , rightsRecordQuery.getResourceId(), orderByList, page, rightsRecordQuery.getResourceRegionalismCode());
        LogUtils.logUpload("民警维权记录列表", "1", rightsRecordQuery.getResourceId(), rightsRecordQuery.getResourceAddress(), json, "", "成功", "","");

        OkHttpUtils.post(rightsRecordQuery.getResourceAddress(), json, QuerySuccessBean.class).compose(this.bindToLifecycle()).subscribe(new ObserverOnNext<QuerySuccessBean>() {
            @Override
            public void onNext(QuerySuccessBean querySuccessBean) {
                dismissLoading();
                mSrl.finishRefresh();
                if (querySuccessBean.getCode().equals("200")) {
                    mAdapter.setNewData(querySuccessBean.getData().getDataList());
                } else {
                    MyToast.show(querySuccessBean.getMessage());
                }
            }
        });
    }


    /**
     * 搜索条件
     */
    private List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> search() {
        String name = mEtSafeguardRights.getText().toString();//维权人
        String id = mEtIdcard.getText().toString();  //维权人身份证号
        String start = mEtStart.getText().toString();//
        String end = mEtEnd.getText().toString();//
        String perpetrator = mEtPerpetrator.getText().toString();//违法人
        if (!TextUtils.isEmpty(end)){
            end+=" 23:59:59";
        }
        List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> list = new ArrayList<>();
        QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean1 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
        bean1.setKey("offendername");
        bean1.setRelationOperator("like");
        bean1.setValue(perpetrator);
        list.add(bean1);
        QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean2 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
        bean2.setKey("policename");
        bean2.setRelationOperator("like");
        bean2.setValue(name);
        list.add(bean2);
        QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean3 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
        bean3.setKey("starttime");
        bean3.setRelationOperator(">=");
        bean3.setValue(start);
        list.add(bean3);
        QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean4 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
        bean4.setKey("endtime");
        bean4.setRelationOperator("<=");
        bean4.setValue(end);
        list.add(bean4);
        return list;
    }

    /**
     * 加载更多
     */
    private void loadmore(List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> keyValueListBeanList) {

        ResourceApi rightsRecordQuery = ResourceApiUtils.getResourceApi(MainActivity.resourceApiList, Constant.rightsRecordQuery);

        mPage += 1;
        showLoading();
        List<QueryBean.ParameterBean.OrderByBean> orderByList = new ArrayList<>();

//        QueryBean.ParameterBean.OrderByBean order1 = new QueryBean.ParameterBean.OrderByBean();
//        order1.setSort("passdate");
//        order1.setSort("desc");
//        orderByList.add(order1);

        QueryBean.ParameterBean.PageBean page = new QueryBean.ParameterBean.PageBean();
        page.setPageNo(mPage);
        page.setPageSize(20);
        String json = JsonUtils.query(keyValueListBeanList, "policename,policetype,offendername,createdate,id"
                , rightsRecordQuery.getResourceId(), orderByList, page, rightsRecordQuery.getResourceRegionalismCode());
        OkHttpUtils.post(rightsRecordQuery.getResourceAddress(), json, QuerySuccessBean.class).compose(this.bindToLifecycle()).subscribe(new ObserverOnNext<QuerySuccessBean>() {
            @Override
            public void onNext(QuerySuccessBean querySuccessBean) {
                dismissLoading();
                mSrl.finishLoadmore();
                if (querySuccessBean.getCode().equals("200")) {
                    if (querySuccessBean.getData().getDataList().size() > 0) {
                        mAdapter.addData(querySuccessBean.getData().getDataList());
                    } else {
                        MyToast.show("没有更多数据了");
                    }
                } else {
                    MyToast.show(querySuccessBean.getMessage());
                }
            }
        });
    }


    /**
     * 初始化上拉刷新 下拉加载更多
     */
    private void initRefresh() {
        //mSrl.setRefreshHeader(new DeliveryHeader(this));

        mSrl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getData(search());
            }
        });
        mSrl.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                loadmore(search());
            }
        });
    }

    /**
     * 显示时间
     */
    private void showTime(int flag) {
        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String time = TimeUtils.date2date(date);
                //1开始时间
                if (flag == 1) {
                    mEtStart.setText(time);
                }
                //结束时间
                if (flag == 2) {
                    mEtEnd.setText(time);
                }

                MyLogger.i(TimeUtils.date2date(date));

            }
        }).setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setBgColor(0xffd6ecf0)
                .setTitleBgColor(0xffd6ecf0)
                .setLabel("年", "月", "日", "", "", "")//默认设置为年月日时分秒
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();

        pvTime.show();
    }


    @OnClick({R.id.et_start, R.id.et_end, R.id.btn_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_start:
                showTime(1);
                break;
            case R.id.et_end:
                showTime(2);
                break;
            case R.id.btn_search:
                getData(search());
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        QuerySuccessBean.DataBean.DataListBean item = (QuerySuccessBean.DataBean.DataListBean) adapter.getData().get(position);
        // MyLogger.i(JsonUtils.queryGetFiled(item.getFieldValues(), "id"));
         Intent intent = new Intent(this, SafeguardRightsActivity.class);
        intent.putExtra("id",  JsonUtils.queryGetFiled(item.getFieldValues(), "id"));
        startActivity(intent);
    }
}
